<?php
namespace App\Service\OrderService\OrderInterfaceService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\PssModel\OrderRefund;
use App\Model\PssModel\OrderRefundLog;
use App\Service\OrderService\OrderRefundService\OrderRefundMessage;

/**
 * BBC同步云仓数据物流发货状态
 * 1、退货退款物流信息
 * 2、换货物流信息
 * 3、补寄
 * 用户确认收货之后，通知云仓售后成功
 */
class OrderNotifyUpstreamAfterSaleFinish extends BaseService
{
    /**
     * 1、退货退款物流信息
     * 2、换货物流信息
     * 3、补寄
     */
    public function index( array $param = [] )
    {
        $binfo  = $param['binfo'];
        $bid    = $binfo['bid'];
        $requestData = $param['requestData'];
        if( empty($requestData['order_refund_id']) ) {
            return Normal::returnCode(Normal::FAIL,"售后order_refund_id不能为空");
        }
        if( empty($requestData['create_user_id']) ) {
            return Normal::returnCode(Normal::FAIL,"售后create_user_id不能为空");
        }
        if( empty($requestData['create_user_name']) ) {
            return Normal::returnCode(Normal::FAIL,"售后create_user_name不能为空");
        }
        
        $order_refund_id = $requestData['order_refund_id'];
        $orderRefund = OrderRefund::instance()->info(['id'=>$order_refund_id]);
        if( empty($orderRefund) ) {
            return Normal::returnCode(Normal::FAIL,"售后信息不存在");
        }
        
        if( $orderRefund['refund_status'] != OrderRefundMessage::refund_status_wait_user_rev_goods ) {
            return Normal::returnCode(Normal::FAIL,"当前售后状态不允许进行售后完结");
        }
        
        try
        {
            OrderRefund::instance()->startTrans();
            $result = OrderRefund::instance()
            ->where('id',$order_refund_id)
            ->where('refund_status',OrderRefundMessage::refund_status_wait_user_rev_goods)
            ->update([
                'refund_status' => OrderRefundMessage::refund_status_after_sale_success
            ]);
            
            if( !$result ) {
                OrderRefund::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"当前售后状态不允许进行售后完结");
            }
            
            $refund_type_name = OrderRefund::instance()->refund_type[$orderRefund['refund_type']];
            //写入订单日志
            OrderRefundLog::instance()->addLog($order_refund_id,"用户确认收货-[{$refund_type_name}]", $requestData['create_user_id'], $requestData['create_user_name']);
            OrderRefund::instance()->commit();
            return Normal::returnCode(Normal::SUC,"售后完结处理成功");
        } 
        catch ( \Throwable $th)
        {
            OrderRefund::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"售后完结处理失败:{$th->getMessage()}，请联系管理员进行核实处理");
        }
    }
}